import axios from 'axios'
import request from '@/utils/request.js'
import store from '@/store'
/**
 * 导出
 * @param {string} url 导出的文件流
 * @param {object} data 附带的参数
 * @param {boolean} paramOnUrl 参数是否放在url上，默认放在请求体中
 * @return {File} 导出文件
 * */
export function createDownloadLink (url, data, paramOnUrl = false) {
  let requestUrl = url
  let requestData = data
  // 如果需要将参数放在url上
  if (paramOnUrl) {
    requestUrl = `${requestUrl}${objectToQuery(data)}`
    requestData = {}
  }
  axios
    .post(requestUrl, requestData, { responseType: 'blob' })
    .then(function (res) {
      let fileName = res.headers['content-disposition']
        .split(';')[1]
        .split('filename=')[1]
      fileName = decodeURIComponent(fileName)
      const url = window.URL.createObjectURL(new Blob([res.data]))
      const link = document.createElement('a')
      link.href = url
      link.setAttribute('download', fileName)
      document.body.appendChild(link)
      link.click()
    })
}

// 转换参数
function objectToQuery () {
  const obj = arguments[0]
  const prefix = arguments[1]
  if (typeof obj !== 'object') return ''
  const attrs = Object.keys(obj)
  return attrs.reduce((query, attr, index) => {
    // 判断是否是第一层第一个循环
    if (index === 0 && !prefix) query += '?'
    if (typeof obj[attr] === 'object') {
      const subPrefix = prefix ? `${prefix}[${attr}]` : attr
      query += this.objectToQuery(obj[attr], subPrefix)
    } else {
      if (prefix) {
        query += `${prefix}[${attr}]=${obj[attr]}`
      } else {
        query += `${attr}=${obj[attr]}`
      }
    }
    // 判断是否是第一层最后一个循环
    if (index !== attrs.length - 1) query += '&'
    return query
  }, '')
}

// 带请求头
export function download2Plus (url, params, isImg = false) {
  if (isImg) {
    downloadImg(url, params)
    return
  }
  let downLink = url
  if (params) downLink = `${downLink}${objectToQuery(params)}`
  console.log(store.getters.token, 'store.getters.tokenstore.getters.token')

  request({
    url: downLink,
    method: 'get',
    responseType: 'blob'
  }).then((res) => {
    if (res.status === 200) {
      const elink = document.createElement('a')
      elink.download = decodeURI(
        res.headers['content-disposition'].split('attachment;filename=')[1]
      )
      elink.style.display = 'none'
      elink.href = window.URL.createObjectURL(res.data)
      elink.click()
      window.URL.revokeObjectURL(url)
    }
  })
}

export function download2 (url, params, isImg = false) {
  if (isImg) {
    downloadImg(url, params)
    return
  }
  console.log(url)
  console.log(params)
  let downLink = url
  if (params) downLink = `${downLink}${objectToQuery(params)}`
  // 创建a标签，用于跳转至下载链接
  const tempLink = document.createElement('a')
  tempLink.style.display = 'none'
  tempLink.href = downLink
  // tempLink.setAttribute('download', '1.doc')
  // 兼容：某些浏览器不支持HTML5的download属性
  if (typeof tempLink.download === 'undefined') {
    tempLink.setAttribute('target', '_blank')
  }
  // 挂载a标签
  document.body.appendChild(tempLink)
  tempLink.click()
  document.body.removeChild(tempLink)
  // 释放blob URL地址
  window.URL.revokeObjectURL(url)
}

// 下载图片
export function downloadImg (file) {
  const image = new Image()
  // 解决跨域 Canvas 污染问题
  image.setAttribute('crossOrigin', 'anonymous')
  image.onload = function () {
    const canvas = document.createElement('canvas')
    canvas.width = image.width
    canvas.height = image.height
    const context = canvas.getContext('2d')
    context.drawImage(image, 0, 0, image.width, image.height)
    const url = canvas.toDataURL('image/png') // 得到图片的base64编码数据
    const a = document.createElement('a') // 生成一个a元素
    const event = new MouseEvent('click') // 创建一个单击事件
    a.download = file.originalFileName // 设置图片名称
    a.href = url // 将生成的URL设置为a.href属性
    a.dispatchEvent(event) // 触发a的单击事件
  }
  image.src = file.path
}

// 下载视频
export function downloadVideo (file) {
  fetch(file.path)
    .then((res) => {
      return res.blob()
    })
    .then((data) => {
      const a = document.createElement('a')
      const objectUrl = window.URL.createObjectURL(data)
      a.download = name
      a.href = objectUrl
      a.click()
      window.URL.revokeObjectURL(objectUrl)
      a.remove()
    })
}

// 下载流文件
function downloadBlobFile (method, url) {
  const request = new XMLHttpRequest()
  request.open(method, url)
  request.send()
  request.responseType = 'blob'
  return request
}

// 下载音频
export function downloadAudio (file) {
  downloadBlobFile('get', file.path).onreadystatechange = (res) => {
    if (
      res.currentTarget.readyState === 4 &&
      res.currentTarget.status === 200
    ) {
      const url = window.URL.createObjectURL(res.currentTarget.response)
      const a = document.createElement('a')
      a.href = url
      a.download = file.originalFileName
      a.click()
    }
  }
}
